import { Command } from "commander";
import ora from "ora";
import prompts from "prompts";
import Logger from "../../utils/log";
import ICommand from "../ICommand";

export function getCommand(): Command {
  return new Command("a")
    .alias("askAi")
    .description("向Asuka助手提问")
    .action(() => new AskCommand().execute());
}

class AskCommand implements ICommand{
  private messages: { role: "user" | "assistant"; content: string }[] = [];

  async execute():Promise<void> {
    while (true) {
      const question = await this.promptForQuestion();
      if (!question || ["exit", "quit"].includes(question.toLowerCase())) {
        Logger.info("👋 已退出对话模式，我们下次见！ ✨");
        break;
      }

      this.messages.push({ role: "user", content: question });
      const res = await this.askSparkStream();

      if (res) {
        this.messages.push({ role: "assistant", content: res });
      } else {
        console.log("\n🤖：没有返回内容");
      }
    }
  }

  private async promptForQuestion() {
    const { question } = (await prompts({
      type: "text",
      message: "请输入与项目相关的问题(输入exit或quit退出)",
      name: "question",
    })) as { question: string };

    if (!question || question.length > 200) {
      return null;
    }
    return question;
  }

  private async askSparkStream(): Promise<string | undefined> {
    const myHeaders = new Headers();
    myHeaders.append("Authorization", "Bearer gbwCDxSqGJcBhSDPsbLx:TtqRziJMyUQyDKjPUGnZ");
    myHeaders.append("Content-Type", "application/json");

    const data = JSON.stringify({
      model: "lite",
      messages: this.messages,
      stream: true,
    });

    const spinner = ora("🤖 思考中...").start();

    try {
      const res = await fetch("https://spark-api-open.xf-yun.com/v1/chat/completions", {
        method: "POST",
        headers: myHeaders,
        body: data,
      });

      if (!res.body) throw new Error("No response body");

      spinner.stop();
      const reader = res.body.getReader();
      const decoder = new TextDecoder();

      let finalContent = "";

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk
          .split("\n")
          .map((line) => line.trim())
          .filter((line) => line.startsWith("data:"));

        for (const line of lines) {
          const jsonStr = line.replace("data: ", "");
          if (jsonStr === "[DONE]") break;

          try {
            const json = JSON.parse(jsonStr);
            const delta = json.choices?.[0]?.delta?.content;
            if (delta) {
              await this.typeWriter(delta);
              finalContent += delta;
            }
          } catch {
            // 忽略解析失败的 JSON 行
          }
        }
      }

      console.log(); // 打印换行
      return finalContent;
    } catch (error) {
      spinner.stop();
      Logger.fail("🚀 出错:"+error);
    }
  }

  private async typeWriter(text: string, delay: number = 25) {
    for (const char of text) {
      process.stdout.write(char);
      await new Promise((resolve) => setTimeout(resolve, delay));
    }
  }
}
